<template>
  <abstract-dialog
    :loading="loading"
    :title="title"
    :value="value"
    @close="cancel"
    @open="open"
  >
    <abstract-form :model="form" :rules="rules" label-width="120px">
      <el-form-item label="工作小结文件" prop="fileList">
        <el-upload
          ref="upload"
          action="http://0.0.0.0"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="form.fileList"
          :auto-upload="false"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
        </el-upload>
      </el-form-item>
    </abstract-form>

    <template v-slot:footer>
      <el-button plain size="small" @click="closeDialog">取 消</el-button>
      <el-button size="small" type="primary" @click="confirm">确 定</el-button>
    </template>
  </abstract-dialog>
</template>

<script>
import AbstractDialog from '@/components/abstract/Dialog'
import dialogMixin from '@/mixin/dialogMixin'
import AbstractForm from '@/components/abstract/Form'
import { elSuccess } from '@/utils/message'
import { fileUpload } from '@/api/request'

export default {
  name: 'UpdateFileDialog',

  components: {
    AbstractDialog,
    AbstractForm
  },

  mixins: [dialogMixin],

  props: {
    value: Boolean,
    data: { type: Object, default: () => ({}) },
    id: {
      type: Number,
      default: NaN
    }
  },

  data() {
    const validateFileList = (rule, value, callback) => {
      if (this.$refs.upload.uploadFiles.length === 0) {
        callback(new Error('请上传工作小结'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      title: '上传工作小结',
      form: {
        fileList: []
      },
      rules: {
        fileList: [{ validator: validateFileList, trigger: 'blur' }]
      }
    }
  },

  methods: {
    open() {
      this.isUpdateData = true
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },

    clearForm() {
      this.form.fileList = []
      this.$nextTick(() => this.$refs.form.clearValidate())
    },

    cancel() {
      this.closeDialog()
      this.clearForm()
    },

    confirm() {
      if (this.loading) return
      this.$refs.form.validate((v) => {
        if (!v) return
        this.loading = true
        const promise = fileUpload(
          'personal/myWorkSummary/upload',
          this.$refs.upload.uploadFiles[0].raw,
          {
            id: this.id
          },
          () => {}
        )
        promise
          .then(() => {
            elSuccess()
            this.$emit('success')
            this.cancel()
          })
          .finally(() => this.$nextTick(() => (this.loading = false)))
      })
    }
  }
}
</script>
